﻿using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.Collections;
using System;
using System.Data;
using System.Web.UI.HtmlControls;
namespace DreamBuilder.UI.UserControls
{
    [DefaultProperty("Text"), ToolboxData("<{0}:EPGridView runat=server></{0}:EPGridView>")]
    public class EPGridView : System.Web.UI.WebControls.GridView
    {
        #region 变量
        private bool showcheckBox = false;
        private string emptyDataCellCssClass;
        private bool enableEmptyContentRender = true;
        private ArrayList _selectItems = null;
        private bool IsSorted = false;
        private string sortField = "";
        private int _recordCount = 0;

        private static string selectpagerid;
        #endregion

        #region 属性
        /// <summary>
        /// 是否数据为空时显示标题行
        /// </summary>
        public bool EnableEmptyContentRender
        {
            set { enableEmptyContentRender = value; }
            get { return enableEmptyContentRender; }
        }

        /// <summary>
        /// 为空时信息单元格样式类
        /// </summary>
        public string EmptyDataCellCssClass
        {
            set { emptyDataCellCssClass = value; }
            get { return emptyDataCellCssClass; }
        }
        /// <summary>
        /// 是否显示选中行(默认选中)
        /// </summary>
        public bool ShowCheckBox
        {
            set { showcheckBox = value; }
            get { return showcheckBox; }
        }

        /// <summary>
        /// 页面数据的条数   add by guoyin
        /// </summary>
        public int GvPageCount
        {
            set { ViewState["GvPageCount"] = value; }
            get {return Convert.ToInt32(ViewState["GvPageCount"]); }
            
        }


        /// <summary>
        /// 选中的行(存储主键)
        /// </summary>
        [Browsable(false)]
        public ArrayList SelectItems
        {
            get
            {
               
                if (showcheckBox)
                {
                    try
                    {
                        _selectItems = new ArrayList();
                        for (int i = 0; i < this.Rows.Count; i++)
                        {
                            string id = this.DataKeys[i].Value.ToString();
                            foreach (TableCell tc in this.Rows[i].Cells)
                            {
                                if (tc.Controls.Count > 0 && tc.Controls[0] is CheckBox)
                                {
                                    CheckBox cb = tc.Controls[0] as CheckBox;
                                    if (!_selectItems.Contains(id) && cb.Checked)
                                        _selectItems.Add(id);
                                }
                            }
                        }
                        return _selectItems;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 排序方向
        /// </summary>
        public string sortDirection
        {
            get
            {
                if (ViewState["sortDirection"] != null)
                {
                    return ViewState["sortDirection"].ToString();
                }
                else
                {
                    ViewState["sortDirection"] = "ASC";
                    return ViewState["sortDirection"].ToString();
                }
            }
            set
            {
                ViewState["sortDirection"] = value;
            }
        }
        /// <summary>
        /// 数据源排序（sortField+” “+sortDirection）
        /// </summary>
        public string dataSortExpression
        {
            get
            {
                if (ViewState["dataSortExpression"] != null)
                {
                    return ViewState["dataSortExpression"].ToString();
                }
                else
                {
                    ViewState["dataSortExpression"] = string.Empty;
                    return ViewState["dataSortExpression"].ToString();
                }
            }
            set
            {
                ViewState["dataSortExpression"] = value;
            }
        }


        /// <summary>
        /// 跳转到的页面
        /// </summary>
        [Browsable(false)]
        public int Goto
        {
            get
            {
                if (ViewState["goto"] != null)
                {
                    return int.Parse(ViewState["goto"].ToString());
                }
                else
                {
                    ViewState["goto"] = 0;
                    return int.Parse(ViewState["goto"].ToString());
                }
            }
            set
            {
                ViewState["goto"] = value;
            }
        }

        /// <summary>
        /// 每页显示的条数
        /// </summary>
        public int ShowRecordsCount
        {
            get
            {
                object obj = ViewState["ShowRecordsCount"];
                return (obj == null) ? int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageSize"]) : (int)ViewState["ShowRecordsCount"];
            }
            set { ViewState["ShowRecordsCount"] = value; }
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        private object ViewDataSource
        {
            get
            {
                if (ViewState["dtList"] != null)
                {
                    return ViewState["dtList"];
                }
                else
                {
                    ViewState["dtList"] = this.DataSource;
                    return ViewState["dtList"];
                }
            }
            set
            {
                ViewState["dtList"] = value;
            }
        }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int RecordCount
        {
            get
            {
                return _recordCount;
            }
        }
        #endregion

        #region 定义委托
        /// <summary>
        /// 分页事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        protected void EPGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            //如果已经用这一列排序了的，则改为降序
            string _sortDirection = ColumnsSortedDirection(e.SortExpression);
            if (_sortDirection != string.Empty)
            {
                if (_sortDirection == "ASC")
                {
                    sortDirection = "DESC";
                }
                else
                {
                    sortDirection = "ASC";
                }
            }
            else
            {
                if (e.SortDirection == SortDirection.Ascending)
                {
                    sortDirection = "ASC";
                }
                if (e.SortDirection == SortDirection.Descending)
                {
                    sortDirection = "DESC";
                }
            }
            sortField = e.SortExpression;
            IsSorted = false;
            this.DataSource = ViewDataSource;
            SortData(IsSorted);
            this.DataBind();
        }
        #endregion


        #region 重写控件事件
        /// <summary>
        /// Init事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            if (showcheckBox)
            {
                AddITemplateCheck();
            }
            AddPagerTemplate();
            base.OnInit(e);
        }

        /// <summary>
        /// 加载事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            string postBackId = this.Page.Request["__EVENTTARGET"];
            if (!string.IsNullOrEmpty(postBackId) && postBackId.Contains("_desp_select"))
            {
                //ShowRecordsCount = int.Parse(this.Page.Request[postBackId]);
                ViewState["epagesize"] = int.Parse(this.Page.Request[postBackId]);
            }
            if (ViewState["epagesize"] != null)
                this.PageSize = int.Parse(ViewState["epagesize"].ToString());
            else
            {
                this.PageSize = ShowRecordsCount;
            }
            this.Sorting += new GridViewSortEventHandler(EPGridView_Sorting);
            this.PageIndexChanging+=new GridViewPageEventHandler(EPGridView_PageIndexChanging);
            if (this.DataSource != null)
            {
                if (this.DataSource is DataView)
                {
                    this.ViewDataSource = ((DataView)this.DataSource).ToTable();
                }
                else
                {
                    this.ViewDataSource = this.DataSource;
                }
            }
            if (this.ViewDataSource != null)
            {
                this.DataSource = this.ViewDataSource;
            }
            base.OnLoad(e);
        }

        protected void EPGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.PageIndex = e.NewPageIndex;
            this.DataSource = ViewDataSource;
            this.DataBind();
        }

        protected override void OnDataBinding(EventArgs e)
        {
            if (this.DataSource != null)
            {
                if (this.DataSource is DataView)
                {
                    this.ViewDataSource = ((DataView)this.DataSource).ToTable();
                    this._recordCount = (this.ViewDataSource as DataTable).Rows.Count;
                }
                else
                {
                    this.ViewDataSource = this.DataSource;
                    if (this.ViewDataSource is DataTable)
                    {
                        this._recordCount = (this.ViewDataSource as DataTable).Rows.Count;
                    }
                    if (this.ViewDataSource is DataSet)
                    {
                        this._recordCount = (this.ViewDataSource as DataSet).Tables[0].Rows.Count;
                    }
                    if (this.ViewDataSource is IList)
                    {
                        this._recordCount = (this.ViewDataSource as IList).Count;
                    }
                }
            }
            base.OnDataBinding(e);
        }

        protected override void OnRowDataBound(GridViewRowEventArgs e)
        {
            base.OnRowDataBound(e);
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //储存状态
                ArrayList select = ViewState["selectItems"] == null ? SelectItems : ViewState["selectItems"] as ArrayList;
                //储存选择状态
                if (select != null)
                {
                    //主键ID[如果没有配置主键，会抛出异常]
                    string id = this.DataKeys[e.Row.RowIndex].Value.ToString();
                    foreach (TableCell tc in e.Row.Cells)
                    {
                        if (tc.Controls.Count > 0 && tc.Controls[0] is CheckBox)
                        {
                            CheckBox cb = tc.Controls[0] as CheckBox;
                            if (select.Contains(id))
                                cb.Checked = true;
                            if (!select.Contains(id))
                                cb.Checked = false;
                        }
                    }
                }
                //更改选择行的颜色
                e.Row.Attributes.Add("onclick", "javascript:return ClickSetColor(this);");
                e.Row.Attributes.Add("onmouseover", "javascript:MouseOnSetColor(this);");
                e.Row.Attributes.Add("onmouseout", "javascript:MouseOutCancelColor(this);");
            }
            if (e.Row.RowType == DataControlRowType.Pager)
            {
                Label lbPage = (Label)e.Row.FindControl("lbPage");
                lbPage.Text = "第 <span style='color:red;'>" + (this.PageIndex + 1) + "</span> 页/共 <span style='color:red;'>" + this.PageCount + "</span> 页 共 <span style='color:red;'>" + this._recordCount + "</span> 条";

                //如果是首页，前一页不可用
                if (this.PageIndex == 0)
                {
                    LinkButton btnPrev = (LinkButton)e.Row.FindControl("btnPrev");
                    btnPrev.Enabled = false;
                }
                //如果是下一页，则末页不可用
                if (this.PageIndex == this.PageCount - 1)
                {
                    LinkButton btnNext = (LinkButton)e.Row.FindControl("btnNext");
                    btnNext.Enabled = false;
                }
            }
        }

        protected override void OnRowCommand(GridViewCommandEventArgs e)
        {
            base.OnRowCommand(e);
            if (e.CommandName == "goto")
            {
                int index = 0;
                TextBox t = ((TextBox)this.BottomPagerRow.FindControl("txtPageInex"));
                if (t.Text != string.Empty)
                {
                    int.TryParse(t.Text, out index);
                    Goto = index - 1;
                    GridViewPageEventArgs args = new GridViewPageEventArgs(Goto);
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (enableEmptyContentRender && (this.Rows.Count == 0 || this.Rows[0].RowType == DataControlRowType.EmptyDataRow))
            {
                RenderEmptyContent(writer);
            }
            else
            {
                base.Render(writer);
            }
        }

        #endregion

        #region 私有方法
        /// <summary>
        /// 增加选中列模板
        /// </summary>
        private void AddITemplateCheck()
        {
            //bool bStatus =ViewState["gvAllCheck"] == null ? false :  (bool)ViewState["gvAllCheck"];
            TemplateField templateField = new TemplateField();
            templateField.HeaderStyle.Wrap = false;
            templateField.HeaderStyle.Width = Unit.Percentage(4);
            templateField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            templateField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            templateField.HeaderTemplate = new ListTemplateCheckHeader();
            templateField.ItemTemplate = new ListTemplateCheckColumn();
            this.Columns.Insert(0, templateField);
        }

        /// <summary>
        /// 设置分页模板
        /// </summary>
        private void AddPagerTemplate()
        {
            this.PagerTemplate = new PagerTemplateRow();
        }

        /// <summary>
        /// 对数据源排序
        /// </summary>
        private void SortData(bool tblChanged)
        {
            if (!tblChanged)
            {
                dataSortExpression = sortField + " " + sortDirection;
                if (!String.IsNullOrEmpty(sortDirection) && !string.IsNullOrEmpty(sortField))
                {
                    if (DataSource is DataSet)
                    {
                        if (((DataSet)DataSource).Tables.Count > 0)
                        {
                            ((DataSet)DataSource).Tables[0].DefaultView.Sort = dataSortExpression;
                            this.DataSource = ((DataSet)DataSource).Tables[0].DefaultView.ToTable();
                        }
                    }
                    else if (DataSource is DataTable)
                    {
                        ((DataTable)DataSource).DefaultView.Sort = dataSortExpression;
                        this.DataSource = ((DataTable)DataSource).DefaultView.ToTable();
                    }
                    else if (DataSource is DataView)
                    {
                        ((DataView)DataSource).Sort = dataSortExpression;
                        this.DataSource = ((DataView)DataSource).ToTable();
                    }
                }
                IsSorted = true;
            }
        }

        /// <summary>
        /// 已经排列的顺序
        /// </summary>
        /// <param name="sortExpression"></param>
        /// <returns></returns>
        private string ColumnsSortedDirection(string sortExpression)
        {
            if (dataSortExpression.Contains(sortDirection))
            {
                int index = dataSortExpression.IndexOf(" ");
                if (index > 0)
                {
                    return dataSortExpression.Substring(index + 1);
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 为空时输出内容
        /// </summary>
        /// <param name="writer"></param>
        protected virtual void RenderEmptyContent(HtmlTextWriter writer)
        {
            Table table = new Table(); //create a table
            table.CssClass = this.CssClass; //copy all property
            table.GridLines = this.GridLines;
            table.BorderStyle = this.BorderStyle;
            table.BorderWidth = this.BorderWidth;
            table.CellPadding = this.CellPadding;
            table.CellSpacing = this.CellSpacing;
            table.HorizontalAlign = this.HorizontalAlign;

            table.Width = this.Width;

            table.CopyBaseAttributes(this);

            TableRow row = new TableRow();

            row.CssClass = this.HeaderStyle.CssClass;

            table.Rows.Add(row);
            int showCols = 0;
            foreach (DataControlField dataControlField in this.Columns) //generate table header
            {
                string lsText = string.Empty;
                if (dataControlField.Visible == true)
                {
                    showCols++;
                    TableHeaderCell cell = new TableHeaderCell();

                    cell.Text = "";

                    if (dataControlField is BoundField)
                    {
                        cell.Text = ((BoundField)dataControlField).HeaderText;
                    }
                    else if (dataControlField is TemplateField)
                    {
                        cell.Text = ((TemplateField)dataControlField).HeaderText;
                    }
                    else
                    {
                        cell.Text = dataControlField.HeaderText;
                    }

                    cell.Width = dataControlField.HeaderStyle.Width;

                    cell.CssClass = dataControlField.HeaderStyle.CssClass;// "CL-childTable-head"; //这里把表头样式写死了

                    row.Cells.Add(cell);
                }
            }

            TableRow row2 = new TableRow();
            table.Rows.Add(row2);

            TableCell msgCell = new TableCell();
            msgCell.CssClass = this.emptyDataCellCssClass;

            if (this.EmptyDataTemplate != null) //the second row, use the template
            {
                this.EmptyDataTemplate.InstantiateIn(msgCell);
            }
            else //the second row, use the EmptyDataText
            {
                if (this.EmptyDataText != string.Empty)
                {
                    msgCell.Text = this.EmptyDataText;
                }
                else
                {
                    msgCell.Text = "<div style='text-align:center;'><span style='color:red;'>没有数据</span></div>";
                }
            }

            msgCell.HorizontalAlign = HorizontalAlign.Center;
            msgCell.ColumnSpan = showCols;

            row2.Cells.Add(msgCell);
            table.RenderControl(writer);
        }
        #endregion

        public void ResetSelectItemsInViewState(ArrayList SelectItems)
        {
            try
            {
                ViewState["selectItems"] = SelectItems;
            }
            catch (Exception)
            { }
        }
    }


    /// <summary>
    /// 指定分页模板
    /// </summary>
    public class PagerTemplateRow : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            Table table = new Table();
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            //加入页码
            Label lbPage = new Label();
            lbPage.Text = "总共有几页";
            lbPage.ID = "lbPage";
            lbPage.Style.Add(HtmlTextWriterStyle.MarginRight, "50px");
            cell.Controls.Add(lbPage);
            //加入按钮(首页)
            LinkButton linkBtnFirst = new LinkButton();
            linkBtnFirst.ID = "btnFirst";
            linkBtnFirst.CommandName = "Page";
            linkBtnFirst.CommandArgument = "First";
            Image img1 = new Image();
            img1.ImageUrl = "~/Images/NewGrid/page+.png";
            linkBtnFirst.Controls.Add(img1);
            cell.Controls.Add(linkBtnFirst);
            //加入按钮(上一页)
            System.Web.UI.WebControls.LinkButton linkBtnPrev = new LinkButton();
            linkBtnPrev.ID = "btnPrev";
            linkBtnPrev.CommandName = "Page";
            linkBtnPrev.CommandArgument = "Prev";
            img1 = new Image();
            img1.ImageUrl = "~/Images/NewGrid/page+-.png";
            linkBtnPrev.Controls.Add(img1);
            cell.Controls.Add(linkBtnPrev);
            //加入按钮(下一页)
            System.Web.UI.WebControls.LinkButton linkBtnNext = new LinkButton();
            linkBtnNext.ID = "btnNext";
            linkBtnNext.CommandName = "Page";
            linkBtnNext.CommandArgument = "Next";
            img1 = new Image();
            img1.ImageUrl = "~/Images/NewGrid/page-+.png";
            linkBtnNext.Controls.Add(img1);
            cell.Controls.Add(linkBtnNext);

            //加入按钮(末页)
            System.Web.UI.WebControls.LinkButton linkBtnLast = new LinkButton();
            linkBtnLast.ID = "btnLast";
            linkBtnLast.CommandName = "Page";
            linkBtnLast.CommandArgument = "Last";
            img1 = new Image();
            img1.ImageUrl = "~/Images/NewGrid/page-.png";
            linkBtnLast.Controls.Add(img1);
            cell.Controls.Add(linkBtnLast);

            //输入页码
            System.Web.UI.WebControls.TextBox txtPageInex = new TextBox();
            txtPageInex.Width = Unit.Pixel(30);
            txtPageInex.Height = Unit.Pixel(15);
            txtPageInex.ID = "txtPageInex";
            //跳转到
            System.Web.UI.WebControls.LinkButton linkBtnGoto = new LinkButton();
            linkBtnGoto.ID = "btnGoto";
            linkBtnGoto.CommandName = "goto";
            linkBtnGoto.CommandArgument = txtPageInex.Text;
            img1 = new Image();
            img1.ImageUrl = "~/Images/NewGrid/go.png";
            linkBtnGoto.Controls.Add(img1);

            string script = "enteryKeyEvent(this);";
            txtPageInex.Attributes.Add("onkeydown", "" + script + "");
            cell.Controls.Add(txtPageInex);
            cell.Controls.Add(linkBtnGoto);
            row.Cells.Add(cell);
            table.Rows.Add(row);
            container.Controls.Add(table);
        }
    }
}